﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Grain.Crm.DataMigrator.CrmServices;

namespace Grain.Crm.DataMigrator.Imports
{
    public class ContactImport : ImportBase
    {
        public ContactImport(CrmService service, WhoAmIResponse whoAmIresponse, ImportPayload importPayload)
            : base(service, whoAmIresponse, importPayload)
        {
        }

        protected override void Preprocess(out bool entityExists)
        {

            ImportsGlobal.Contact = FileContent.GetByHeading(HeaderRow, "First Name") + " " +
                                    FileContent.GetByHeading(HeaderRow, "Last Name");

            var companyValue = FileContent.GetByHeading(HeaderRow, "Company");
            var companyId = ImportsHelper.GetEntityId(_service, EntityName.account.ToString(), new string[] { "name" }, new string[] { companyValue });

            var professionId = ImportsHelper.GetEntityId(_service, EntityName.new_profession.ToString(), new string[] { "new_name" }, new string[] { "Assistant" });

            if (companyId == null)
            {
                FileContent = FileContent.RemoveByHeading(HeaderRow, "Company");
                ConsoleLog.Warning("Referenced Company was not found. Ignoring it. Company: " + companyValue);
            }

            var contactId = ImportsHelper.GetEntityId(_service, ThisEntityName, new string[] { "fullname", "birthdate" }, new string[] { ImportsGlobal.Contact, FileContent.GetByHeading(HeaderRow, "Birthday") });

            if (contactId != null)
            {
                entityExists = true;

                ImportsHelper.AddKeyValueToContent(contactId.Value, ThisEntityName, ref HeaderRow, ref FileContent);
            }
            else
                entityExists = false;


            HeaderRow += ",Role";
            FileContent += ",Candidate";

        }

        protected override void Postprocess()
        {
            var contactId = ImportsHelper.GetEntityId(_service, ThisEntityName, new string[] { "fullname", "birthdate" }, new string[] { ImportsGlobal.Contact, FileContent.GetByHeading(HeaderRow, "Birthday") });
            
            ImportsGlobal.ContactId = contactId.Value.ToString();
        }
    }
}
